#include "thread.h"

namespace SMysqlSpace {
	CThread::CThread() : m_thread(INIT_THREAD_ID), m_Status(READY) {
	}

	CThread::~CThread() {
	}

	void CThread::start() {
		if (m_Status != READY) return;
		THREAD_START(m_thread, MyThreadProcess, this);
	}

	void CThread::stop() {
	}

	void CThread::exit(void* retval) {
		THREAD_EXIT(m_thread, retval);
	}

	void CThread::run() {
		// Derived class must implement this interface.
	}

	void CThread::join() {
		THREAD_JOIN(m_thread);
	}

	// windows os like thread function.
	THREAD_FN CThread::MyThreadProcess(void* derivedThread) {
		CThread* poThread = (CThread*)derivedThread;
		if (!poThread) return NULL;

		// set thread's status to "RUNNING"
		poThread->setStatus(RUNNING);

		// derived::run() called
		poThread->run();

		// set thread's status to "EXIT"
		poThread->setStatus(EXIT);

		// join
		poThread->join();

		// exit.
#if (defined(WIN32) || defined(WIN64))
		poThread->exit(NULL);
#else
		int ret = 0;
		poThread->exit(&ret);
#endif
		return THREAD_RETURN;
	}
}
